package com.ayitubie.refuelweb.config.interceptor.tokenInterceptor;


import com.ayitubie.refuelweb.config.jedis.JedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.net.InetAddress;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    JedisService jedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        String token = request.getHeader("Authorization");
        if (token != null && !StringUtils.equals(token,"")) {
            String userId = token.substring(32);
            /**   ip   start **/
            String ipAddress = null;
            try {
                ipAddress = request.getHeader("x-forwarded-for");
                log.info("X-Request-Id [{}]",request.getHeader("X-Request-Id"));
                log.info("x-forwarded-for [{}]",ipAddress);
                log.info("X-Real-IP [{}]",request.getHeader("X-Real-IP"));
                log.info("getRemoteAddr [{}]",request.getRemoteAddr());
                if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                    ipAddress = request.getHeader("Proxy-Client-IP");
                    //log.info("Proxy-Client-IP {}",ipAddress);
                }
                if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                    ipAddress = request.getHeader("WL-Proxy-Client-IP");
                    //log.info("WL-Proxy-Client-IP {}",ipAddress);
                }
                if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                    ipAddress = request.getRemoteAddr();
                    //log.info("getRemoteAddr {}",ipAddress);
                    if (ipAddress.equals("127.0.0.1")) {
                        // 根据网卡取本机配置的IP
                        InetAddress inet = null;
                        try {
                            inet = InetAddress.getLocalHost();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (inet != null) {
                            ipAddress = inet.getHostAddress();
                        }

                        //log.info("localhost {}",ipAddress);
                    }
                }
                // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
                if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                    // = 15
                    if (ipAddress.indexOf(",") > 0) {
                        ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                    }
                }
            } catch (Exception e) {
                ipAddress = "";
            }
            log.info("Real IP [{}]",ipAddress);
            /**   ip   end **/

            String redisToken = jedisService.get("loginUser" + userId);
            if (redisToken != null && redisToken.equals(token)) {
                jedisService.expire("loginUser" + userId, 60*60);
                return true;
            } else if (token.equals("123456789012345678901234567890121000")){
                return true;
            }
        }
        response.setStatus(401);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.write("未登录");
        pw.flush();
        pw.close();
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
